<template>
  <!-- 修改 法人信息 -->
  <view class="root">
    <view class="placeLegalPerson" v-if="!visibleCamera">
      <view class="wrapper">
        <view class="wrapper-item content">
          <u-form :model="form" ref="form" label-width="120" :error-type="errorType">
            <view class="title-name">身份信息</view>
            <u-form-item label="国籍" borderBottom :required="true" @click="hadleShowPicker('nation', 'nationality')">
              <u--input v-model="form.nationality_text" border="none" disabled disabledColor="#fff" placeholder="请选择"
                :maxlength="30"></u--input>
            </u-form-item>
            <u-form-item label="证件类型" borderBottom :required="true"
              @click="hadleShowPicker('certificate_type', 'idType')">
              <u--input v-model="form.idType_text" border="none" disabled disabledColor="#fff" placeholder="请选择"
                :maxlength="30"></u--input>
            </u-form-item>
            <u-form-item label="证件号码" borderBottom :required="true">
              <view style="display: flex;">
                <u--input :type="form.idType == 10 ? 'idcard' : 'text'" v-model="form.idCard" border="none"
                  placeholder="请填写" :maxlength="18" @blur="idCardHandle"></u--input>
                <view v-if="form.idType == 10">
                  <u-icon slot="right" name="scan" color="#2488F5" size="21" @click="handleCamera"></u-icon>
                </view>
              </view>
            </u-form-item>
            <!--    <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="1"
              width="310" height="180" :delIconCenter="true" :delIconSize="40">
              <image :src="baseImgUrl + 'card_3.png'" style="width: 640rpx; height: 360rpx"></image>
            </u-upload> -->
            <u-form-item label="姓名" borderBottom :required="true">
              <u--input v-model="form.legalPersonName" border="none" placeholder="请填写" :maxlength="30"></u--input>
            </u-form-item>
            <u-form-item label="出生日期" borderBottom :required="true" @click="handleShowDatetimePicker('birth')">
              <u--input v-model="form.birth" border="none" disabled disabledColor="#fff" placeholder="请选择"
                :maxlength="30"></u--input>
            </u-form-item>
            <u-form-item label="性别" borderBottom :required="true" @click="hadleShowPicker('sex_type', 'sex')">
              <u--input v-model="form.sex_text" border="none" disabled disabledColor="#fff" placeholder="请选择"
                :maxlength="30"></u--input>
            </u-form-item>
            <u-form-item label="民族" borderBottom :required="true" @click="hadleShowPicker('nation', 'nation')">
              <u--input v-model="form.nation_text" border="none" disabled disabledColor="#fff" placeholder="请选择"
                :maxlength="30"></u--input>
            </u-form-item>
            <!-- <u-form-item label="户籍地址" borderBottom :required="true">
              <u--input v-model="form.residenceDetail" border="none" placeholder="请填写" :maxlength="30"></u--input>
            </u-form-item>
            <u-form-item label="户籍地所属区县" borderBottom :required="true">
              <u--input v-model="form.residenceCode_text" @click.native="handleCityPicker('residenceCode')"
                border="none" placeholder="请选择" :maxlength="30" disabled disabledColor="#fff"></u--input>
            </u-form-item>
            <view class="hint" style="font-size: 20rpx; color: #f56c6c;" v-if="areaList.length">
              户籍所属区县由系统自动匹配，如匹配不准确或未匹配到请务必手动修改!
            </view> -->
            <u-form-item label="联系方式" borderBottom required>
              <view class="codeForm">
                <u--input v-model="form.mobile" border="none" placeholder="请填写"></u--input>
              </view>
            </u-form-item>
          </u-form>
        </view>
      </view>

      <view class="btns thispageBtn">
        <button class="cancel-btn lt" type="primary" @click="navBack('back', 1, 1)">
          取消
        </button>
        <button class="submit-btn" type="primary" @click="submitHandle">
          保存
        </button>
      </view>

      <canvas canvas-id="myCanvas" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
        style="position: fixed; top: -9999999999999rpx" @error="error"></canvas>

      <u-picker closeOnClickOverlay v-if="pickerShow" :show="pickerShow" :columns="pickerData" keyName="text"
        @confirm="onPickerConfirm" @cancel="pickerShow = false" @close="pickerShow = false"
        :defaultIndex="defaultIndex"></u-picker>

      <!-- <yy-city-picker :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false"></yy-city-picker> -->
      <yy-city-picker-all v-if="cityPickerVisible" :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false" :default-value="defaultCityCode"></yy-city-picker-all>

    </view>
    <yy-photo-mask :visible.sync="visibleCamera" :baseImgUrl="baseImgUrl" :clientId="clientId"
      :clientSecret="clientSecret" @generateFilePath="onGenerateFilePath" @parsedSuccess="onParsedSuccess">
    </yy-photo-mask>
    <yy-watermark></yy-watermark>
    <lingfeng-timepicker ref="datetimePickerRef" type="date" :defaultData="defaultData" :minDate="minDate"
      :maxDate="maxDate" @change="timeChange"></lingfeng-timepicker>
  </view>
</template>

<script>
  import cityPickerMixin from "../../utils/city-picker-mixin";
  import pickerMixin from "../../utils/picker-mixin";
  import {
    messageDetail,
    updateCompany
  } from "@/api/myself.js";
  import {
    Toast,
    navBack,
    uniTrim,
    checkIDCard,
    getBase64Two,
    useNetWork,
    isLoading,
    getHeader,
    uploadFile,
    setDefaultProvinceCode,
  } from "@/utils/util.js";

  import _ from '@/utils/lodash.js'
  import moment from "../../utils/moment";


  export default {
    name: "placeLegalPerson",
    mixins: [
      pickerMixin, cityPickerMixin
    ],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        options: {},
        form: {
          nationality: 'CHN',
          nationality_text: '中国',
          idType: '10',
          idType_text: '身份证',
          birth: '',
          sex: '',
        },
        errorType: ["none"],
        fileList: [],
        fileList2: [],
        canvasWidth: 0,
        canvasHeight: 0,
        visibleCamera: false,

        areaList: [],
        defaultCityCode: '',
        // 日期相关的
        defaultData: {
          startTime: moment(new Date()).format('YYYY-MM-DD')
        },
        minDate: {
          year: 1800,
          month: 1,
          date: 1
        },
        maxDate: {
          year: new Date().getFullYear(),
          month: new Date().getMonth() + 1,
          date: new Date().getDate()
        },
        datetimePickerRef: null
      };
    },
    onShow() {
      // 新的法人手机号
      uni.$on("mobileNew", (v) => {
        this.form.mobile = v;
      });
    },
    onLoad(options) {
      this.options = options;

      messageDetail({
        companyId: options.id
      }).then((res) => {
        if (res.code == 200) {
          let {
            legalInfo,
          } = res.result;
          const {
            nation,
            nationName,
            residenceCodeName,
            residenceCode,
            nationality,
            nationalityName,
            idType,
            idTypeName,
            birth,
            sex
          } = legalInfo
          this.form = legalInfo;
          this.$set(this.form, 'nation_text', nationName)
          this.$set(this.form, 'nation', nation)
          this.$set(this.form, 'nationality', nationality)
          this.$set(this.form, 'nationality_text', nationalityName)
          this.$set(this.form, 'idType', idType)
          this.$set(this.form, 'idType_text', idTypeName)
          this.$set(this.form, 'birth', birth)
          this.$set(this.form, 'sex', sex)
          this.$set(this.form, 'sex_text', sex == 1 ? '男' : '女')

          // this.$set(this.form, 'residenceCode_text', residenceCodeName)
          // this.$set(this.form, 'residenceCode', residenceCode)
          // this.defaultCityCode = residenceCode
          if (legalInfo.personImage) {
            this.fileList.push({
              url: this.imgPrefix + legalInfo.personImage,
            });
          }
        }
      });
    },
    methods: {
      handleIdCardChange() {
        let params = {
          idCard: this.form.idCard
        }
      },
      navBack,
      idCardHandle() {
        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag && this.form.idType == 10) {
          Toast("请输入正确的证件号码");
          return;
        }
        this.handleIdCardChange()
      },
      afterRead(info) {
        let _this = this;

        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: _this.clientId,
            client_secret: _this.clientSecret,
          },
          success(res) {
            _this.base64Handle(res.data.access_token, info);
          },
        });
      },
      base64Handle(token, info) {
        let _this = this;

        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            uni.request({
              url: `https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${token}`,
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: {
                id_card_side: "front",
                image: res,
                detect_direction: true,
              },
              // success(resbai) {
              //   let { statusCode, data } = resbai;
              //   if (statusCode == 200 && data.words_result["公民身份号码"]) {
              //     _this.$set(
              //       _this.form,
              //       "legalPersonName",
              //       data.words_result.姓名.words
              //     );
              //     _this.$set(
              //       _this.form,
              //       "idCard",
              //       data.words_result.公民身份号码.words
              //     );
              //     _this.$set(
              //       _this.form,
              //       "residenceDetail",
              //       data.words_result.住址.words
              //     );
              //     _this.uploadImage(info.file.url, 20);
              //     return;
              //   }

              //   Toast("未识别");
              //   _this.uploadImage(info.file.url, 20);
              //   // Toast("请上传正确的身份证证件照片");
              // },
              success(resbai) {
                let {
                  statusCode,
                  data
                } = resbai;

                if (statusCode == 200 && data.words_result["姓名"]) {
                  _this.$set(
                    _this.form,
                    "legalPersonName",
                    data.words_result.姓名.words
                  );
                  _this.$set(
                    _this.form,
                    "idCard",
                    data.words_result.公民身份号码.words
                  );
                  // _this.$set(
                  //   _this.form,
                  //   "residenceDetail",
                  //   data.words_result.住址.words
                  // );
                  // 图片旋转  start
                  var yingNum = 0;
                  var direction = data.direction;
                  if (direction != -1 && direction != 0) {
                    if (direction == 1) {
                      //逆时针90°
                      yingNum = 90;
                    } else if (direction == 2) {
                      //逆时针180°
                      yingNum = 180;
                    } else if (direction == 3) {
                      //逆时针270°
                      yingNum = 270;
                    }
                  }

                  if (yingNum) {
                    uni.showLoading({
                      title: "图片加载中",
                    });
                    _this.drapImgLast(info, yingNum);
                    return;
                  }
                  // 图片旋转  end

                  _this.uploadImage(info.file.url, 20);
                  return;
                }

                Toast("未识别");
                _this.uploadImage(info.file.url, 20);
                // Toast("请上传正确的营业执照");
              },
            });
          });
      },
      drapImgLast(info, yingNum) {
        let _this = this;
        const ctx = uni.createCanvasContext("myCanvas", _this);

        uni.getImageInfo({
          src: info.file.url,
          success(res1) {
            let {
              width,
              height,
              path
            } = res1;
            if (yingNum == 90) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, width, width); // 清空画布

              ctx.translate(_this.canvasWidth, 0);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 270) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, height, width); // 清空画布

              ctx.translate(0, _this.canvasHeight - 10);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 180) {
              _this.canvasWidth = width;
              _this.canvasHeight = height;
              ctx.clearRect(0, 0, width, height); // 清空画布

              ctx.translate(_this.canvasWidth, _this.canvasHeight);
              ctx.rotate((-yingNum * Math.PI) / 180);
            }
            ctx.drawImage(path, 0, 0);

            // 将生成的canvas图片，转为真实图片
            ctx.draw(false, () => {
              setTimeout(() => {
                uni.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: "myCanvas",
                  success(res2) {
                    console.log(res2, "RRRRRRRRR");
                    _this.uploadImage(res2.tempFilePath, 20);
                  },
                });
              }, 50);
            });
          },
        });
      },
      uploadImage(fileurl, type) {
        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type: type,
            },
          })
          .then((res) => {
            let {
              fullPath,
              halfPath
            } = res.result;
            if (type == 20) {
              _this.fileList = [];
              _this.fileList.push({
                url: fullPath
              });
              _this.form.personImage = halfPath;
              uni.hideLoading();
            }
          })
          .finally(() => {
            isLoading(false);
          })
      },
      deletePic() {
        this.fileList = [];
        this.form.personImage = "";
      },
      mobileHandle() {
        let data = {
          id: this.options.id,
          mobile: this.form.mobile,
        };
        uni.navigateTo({
          url: `/selfInfo/amendBusiness/legalPersonphone?data=${encodeURIComponent(
          JSON.stringify(data)
        )}`,
        });
      },
      submitHandle() {
        let {
          personImage,
          legalPersonName,
          idCard,
          mobile,
          nation,
          nationality,
          idType,
          birth,
          sex,
          // residenceDetail,
          // residenceCode
        } =
        this.form;

        if (!nationality) {
          Toast('请选择国籍！')
          return
        }
        if (!idType) {
          Toast('请选择证件类型！')
          return
        }
        if (!idCard || !uniTrim(idCard)) {
          Toast("请输入证件号码");
          return;
        }

        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag && idType == 10) {
          Toast("请输入正确的证件号码");
          return;
        }

        if (!legalPersonName || !uniTrim(legalPersonName)) {
          Toast("请输入姓名");
          return;
        }

        let legalPersonRegexp =
          /^[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]*$/;
        if (!legalPersonRegexp.test(legalPersonName) && idType == 10) {
          Toast("姓名只能输入汉字");
          return;
        }

        if (!birth) {
          Toast('请选择出生日期！')
          return
        }
        if (!sex) {
          Toast('请选择性别！')
          return
        }

        if (!nation || !uniTrim(nation)) {
          Toast("请选择民族");
          return;
        }
        // if (!residenceDetail || !uniTrim(residenceDetail)) {
        //   Toast("请输入户籍地址");
        //   return;
        // }
        // if (!residenceCode) {
        //   Toast("请选择户籍地址");
        //   return;
        // }

        let data = {
          companyLegalPersonInfo: {
            id: this.options.id,
            ...this.form
          },
        };

        updateCompany(data).then((res) => {
          if (res.code == 200) {
            Toast("保存成功");
            navBack("back");
            return;
          }
          Toast(res.message);
        });
      },
      handleCamera() {
        this.visibleCamera = true;
      },
      onParsedSuccess({
        userName,
        idcard,
        domicileAddress,
        words_result
      }) {
        this.$set(
          this.form,
          "legalPersonName",
          userName
        );
        this.$set(
          this.form,
          "idCard",
          idcard
        );
        // this.$set(
        //   this.form,
        //   "residenceDetail",
        //   domicileAddress
        // );
        this.handleIdCardChange()
      },
      onGenerateFilePath(file) {
        this.uploadImage(file, 20)
      },
      handleShowDatetimePicker(type) {
        this.dateTimeCelltype = type
        this.$refs.datetimePickerRef.show()
      },
      setBirthdayAdnSex(idCard) {
        const {
          birthDate,
          gender
        } = parseIDCard(idCard)
        this.form.birthday = moment(birthDate).format("YYYY/MM/DD")
        this.form.sex = gender == '男' ? '1' : '2'
        this.form.sex_text = gender
      },
      timeChange(val) {
        // 根据 celltype 进行判断
        if (this.dateTimeCelltype == 'birth') {
          this.form.birth = moment(val).format('YYYY/MM/DD')
        }
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  .placeLegalPerson {
    flex: 1;
    background-color: #f3f3f3;

    .placeLegalPerson-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 30rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 702rpx;
      }

      .content {
        margin: 0 auto;
        height: calc(100vh - 90px);
        overflow-y: auto;
      }
    }

    .title-name {
      font-size: 30rpx;
      font-weight: bold;
    }

    .code-btn {
      color: #2488f5;
      font-size: 28rpx;
    }

    .codeForm {
      display: flex;
      justify-content: space-around;
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }
  }
</style>